package com.yuke.cloud.service.uac.mq.producer;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.yuke.cloud.common.base.constant.MQConstants;
import com.yuke.cloud.common.base.enums.ErrorCodeEnum;
import com.yuke.cloud.common.core.mq.RabbitMetaMessage;
import com.yuke.cloud.common.security.core.properties.SecurityProperties;
import com.yuke.cloud.common.security.core.properties.SmsCodeProperties;
import com.yuke.cloud.common.security.core.validate.code.ValidateCodeException;
import com.yuke.cloud.common.util.RedisKeyUtil;
import com.yuke.cloud.service.api.opc.dto.SendSmsRequest;
import com.yuke.cloud.service.api.uac.exceptions.UacBizException;
import com.yuke.cloud.service.uac.dto.SmsMessage;
import com.yuke.cloud.service.uac.enums.UacSmsTemplateEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/*
 * <p>Company: Copyright (c) 2018. yuke All Rights Reserved. </br> </p>
 * <p>Title：yuke-mall </br> </p>
 * <p>com.yuke.cloud.service.uac.mq.producer Description TODO </br> </p>
 * @Author wg
 * @Date   2019/12/24 15:06
 */
@Slf4j
@Component
public class SendBatchSms {
    @Resource
    private SecurityProperties securityProperties;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public RabbitMetaMessage sendSmsCodeMq(SmsMessage smsMessage) {

        Preconditions.checkArgument(smsMessage != null, "短信参数不能为空");
        String smsTemplateCode = smsMessage.getSmsTemplateCode();
        Preconditions.checkArgument(UacSmsTemplateEnum.isSmsTemplate(smsTemplateCode), "短信模板没有维护");
        UacSmsTemplateEnum templateEnum = UacSmsTemplateEnum.getEnum(smsTemplateCode);

        //检查短信条数
        Integer num = smsMessage.getMobileNo().split(",").length;
        this.checkSendSmsCount(num);

        String msgBody;
        try {

            SendSmsRequest request = new SendSmsRequest();

            request.setMsgType(MQConstants.MQ_OPC_SEND_SMS);
            Map<String, String> map = Maps.newHashMap();
            // 模板参数
            String smsParamName = templateEnum.getDescription();
            // 模板编码
            String templetCode = templateEnum.getTemplateCode();
            //替换模板验证码
            map.put(smsParamName, smsMessage.getSmsCode());
            String param = JSON.toJSONString(map);

            request.setPhoneNumbers(smsMessage.getMobileNo());
            request.setTemplateCode(templetCode);
            request.setTemplateParam(param);
            request.setOutId(smsMessage.getOutId());

            msgBody = JSON.toJSONString(request);
        } catch (Exception e) {
            log.error("发送短信验证码 smsMessage转换为json字符串失败", e);
            throw new UacBizException(ErrorCodeEnum.UAC10011022);
        }

        RabbitMetaMessage  rabbitMetaMessage = new RabbitMetaMessage();
        rabbitMetaMessage.setExchange(MQConstants.BUSINESS_EXCHANGE);
        rabbitMetaMessage.setRoutingKey(MQConstants.BUSINESS_KEY_OPC);
        rabbitMetaMessage.setPayload(msgBody);
        return rabbitMetaMessage;
    }

    private void checkSendSmsCount(Integer num) {
        SmsCodeProperties sms = securityProperties.getCode().getSms();
        String totalSmsCountKey = RedisKeyUtil.getSendSmsCountKey("total", "total");

        Integer totalSmsCount = (Integer) redisTemplate.opsForValue().get(totalSmsCountKey);
        if (totalSmsCount != null && totalSmsCount > sms.getTotalMaxSendCount()) {
            log.error("短信总发送数上限 ");
            throw new ValidateCodeException("短信总发送数上限");
        } else {
            redisTemplate.opsForValue().set(totalSmsCountKey, totalSmsCount == null ? num : totalSmsCount + num, 1, TimeUnit.DAYS);
        }
    }
}
